<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>公共配置</title>
    <link rel="stylesheet" href="../../../static/component/pear/css/pear.css"/>
    <link rel="stylesheet" href="../../../static/component/codemirror5/codemirror.css"/>
    <link rel="stylesheet" href="../../../static/component/codemirror5/lint/lint.css"/>
    <link rel="stylesheet" href="../../../static/component/codemirror5/addon/dialog.css"/>
</head>

<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form layui-inline" style="margin: 0" lay-filter="public-query-form" action="">
            <div class="layui-form-item layui-inline" style="margin: 0">
                <label lang="zh" class="layui-form-label">项目组</label>
                <div class="layui-input-inline">
                    <select id="user-query-select" lay-filter="user-query-select" name="project_group_id"
                            lay-search="">
                        {{range $id,$val := .PGArr}}
                            <option value="{{$val.ID}}">{{$val.Name}}</option>
                        {{end}}
                    </select>
                </div>
            </div>
        </form>
        <div class="layui-layout-right" style="top: 10px;right: 15px;bottom: 15px">
            <button id="configAdd"
                    class="layui-btn  layui-btn-normal">
                <i lang="zh" class="layui-icon layui-icon-add-1">新增配置</i>
            </button>
        </div>
    </div>
</div>

<div class="layui-row layui-col-space15">
    <div class="layui-col-md3">
        <div class="layui-card">
            <div class="layui-card-body" id="divTreeContent" style="overflow: auto">
                <div id="treeContent">
                </div>
            </div>
        </div>
    </div>
    <div class="layui-col-md9">
        <div class="layui-card">
            <div class="layui-card-body" id="divConfigContent" style="overflow: auto">
                <div style="margin-top:12px;margin-bottom: 24px">
                    <div class="layui-btn-group">
                        <button lang="zh" type="button" id="editConfigID" class="layui-btn layui-btn-normal">编辑
                        </button>
                        <button lang="zh" type="button" id="delConfigID" class="layui-btn layui-btn-normal">删除
                        </button>
                        <button lang="zh" type="button" id="historyConfigID" class="layui-btn layui-btn-normal">
                            历史版本
                        </button>
                    </div>
                    <p id="textConfigID" class="layui-word-aux layui-layout-right"
                       style="display: inline-block;top: 20px;right: 15px;height: 38px;vertical-align: middle;line-height: 38px;font-weight: bold;font-size: large">
                    </p>
                </div>
                <div id="configContent" style="overflow: auto"></div>
            </div>
        </div>
    </div>
</div>

<script src="../../../static/component/layui/layui.js"></script>
<script src="../../../static/component/pear/pear.js"></script>
<script src="../../../static/component/codemirror5/codemirror.js"></script>
<script src="../../../static/component/codemirror5/addon/matchbrackets.js"></script>
<script src="../../../static/component/codemirror5/addon/closebrackets.js"></script>
<script src="../../../static/component/codemirror5/addon/active-line.js"></script>
<script src="../../../static/component/codemirror5/addon/dialog.js"></script>
<script src="../../../static/component/codemirror5/addon/search.js"></script>
<script src="../../../static/component/codemirror5/addon/searchcursor.js"></script>
<script src="../../../static/component/codemirror5/lint/lint.js"></script>
<script src="../../../static/component/codemirror5/lint/jsonlint.js"></script>
<script src="../../../static/component/codemirror5/lint/js-yaml.min.js"></script>
<script src="../../../static/component/codemirror5/lint/json-lint.js"></script>
<script src="../../../static/component/codemirror5/lint/yaml-lint.js"></script>
<script src="../../../static/component/codemirror5/mode/javascript.js"></script>
<script src="../../../static/component/codemirror5/mode/properties.js"></script>
<script src="../../../static/component/codemirror5/mode/toml.js"></script>
<script src="../../../static/component/codemirror5/mode/yaml.js"></script>
<script src="../../../static/component/codemirror5/mode/xml.js"></script>
<script>
    window.onload = function () {
        function auto_height() {
            document.getElementById("divTreeContent").style.height = "80vh";
            document.getElementById("divConfigContent").style.height = "80vh";
        }

        auto_height();
        window.onresize = auto_height;
    }

    layui.use(['lang', 'jquery', 'form', 'popup', 'sail', 'tree', 'layer'], function () {
        let popup = layui.popup;
        let $ = layui.jquery;
        let sail = layui.sail;
        let tree = layui.tree;
        let layer = layui.layer;
        let form = layui.form;
        let lang = layui.lang;

        sail.prefilterAjax();

        let projectGroupId = sessionStorage.getItem("jumpPublicWith");
        sessionStorage.removeItem("jumpPublicWith");
        sessionStorage.removeItem("treePublicClickConfigID");
        if (projectGroupId) {
            let options = $('#user-query-select').children();
            options.each(function (index, elem) {
                if ($(elem).val() === projectGroupId) {
                    $(elem).attr('selected', "true");
                }
            })
        }
        form.render('select');

        let cm = new CodeMirror(document.getElementById("configContent"), {
            lineNumbers: true,
            mode: 'null',
            styleActiveLine: true,
            matchBrackets: true,
            autoCloseBrackets: true,
            gutters: ["CodeMirror-lint-markers"],
            lint: true,
            readOnly: true,
        });
        let jumpData = form.val("public-query-form");
        let accessToken = localStorage.getItem("accessToken");

        let renderConfigDetail = function () {
            let configID = sessionStorage.getItem("treePublicClickConfigID")
            if (!configID) {
                // 清空编辑框
                $('#textConfigID').html('');
                cm.getDoc().setValue('');
                cm.setOption("mode", 'null');
                cm.setOption("readOnly", true);
                return
            }
            $.ajax({
                url: '/sail/v1/config/info',
                data: {
                    config_id: configID,
                },
                headers: sail.setAuth(accessToken),
                dataType: 'json',
                type: 'get',
                success: function (result) {
                    sail.checkSuccess(result, function (resp) {
                        let ckstr = resp.data.name + '.' + resp.data.type

                        if (resp.data.is_encrypt) {
                            ckstr += ' 🔐'
                        }
                        $('#textConfigID').html(ckstr);
                        // 渲染编辑框
                        let typeConfig = resp.data.type;
                        cm.setOption("mode", sail.setCMType(typeConfig));
                        cm.getDoc().setValue(resp.data.content);
                    });
                },
                error: sail.ajaxError,
            })
        }

        let editButton = $('#editConfigID')
        editButton.data('status', 'EDIT') // 初始化状态
        editButton.click(function () {
            let configID = sessionStorage.getItem("treePublicClickConfigID")
            if (!configID) {
                return
            }

            let currentStatus = $(this).data('status')
            if (currentStatus === 'SAVE') {
                let content = cm.getValue();
                $.ajax({
                    url: '/sail/v1/config/edit',
                    data: JSON.stringify({
                        config_id: parseInt(configID),
                        content: content,
                    }),
                    contentType: "application/json;charset=utf-8",
                    headers: sail.setAuth(accessToken),
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        sail.checkSuccess(result, function () {
                            popup.success(lang.translate("保存成功"));
                            renderConfigDetail();
                            let editButton = $('#editConfigID')
                            editButton.text(lang.translate('编辑'));
                            editButton.data('status','EDIT');
                            cm.setOption('readOnly', true);
                        });
                    },
                    error: sail.ajaxError,
                })
                return
            }

            // 打开编辑框
            cm.setOption('readOnly', false);
            cm.focus();
            let editButton = $('#editConfigID')
            editButton.text(lang.translate('保存'))
            editButton.data('status','SAVE')
        })

        $('#delConfigID').click(function () {
            let configID = sessionStorage.getItem("treePublicClickConfigID")
            if (!configID) {
                return
            }

            layer.confirm(lang.translate('确定要删除？'), {
                icon: 3,
                title: lang.translate('提示')
            }, function (index) {
                sessionStorage.removeItem("treePublicClickConfigID");
                $.ajax({
                    url: '/sail/v1/config/del',
                    data: JSON.stringify({
                        config_id: parseInt(configID),
                    }),
                    contentType: "application/json;charset=utf-8",
                    headers: sail.setAuth(accessToken),
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        sail.checkSuccess(result, function () {
                            popup.success(lang.translate("删除成功"));

                            renderTree(jumpData.project_group_id);
                            renderConfigDetail();
                        });
                    },
                    error: sail.ajaxError,
                })
                layer.close(index);
            })
        })

        $('#historyConfigID').click(function () {
            let configID = sessionStorage.getItem("treePublicClickConfigID")
            if (!configID) {
                return
            }

            layer.open({
                type: 2,
                title: lang.translate("配置历史"),
                shade: 0.1,
                area: ['900px', '500px'],
                content: '/ui/public/history?' + 'config_id=' + configID,
            })
        })

        let renderTree = function (pgid) {
            $.ajax({
                url: '/sail/v1/config/tree',
                data: {
                    project_id: 0,
                    project_group_id: parseInt(pgid),
                },
                headers: sail.setAuth(accessToken),
                dataType: 'json',
                type: 'get',
                success: function (result) {
                    sail.checkSuccess(result, function (resp) {
                        tree.render({
                            elem: '#treeContent',  //绑定元素
                            data: resp.data,
                            id: "treeConfig",
                            click: function (obj) {
                                if (obj.data.children) {
                                    return
                                }
                                if (!obj.data.config_id) {
                                    return
                                }
                                sessionStorage.setItem("treePublicClickConfigID", obj.data.config_id);
                                renderConfigDetail();
                            }
                        });
                    });
                },
                error: sail.ajaxError,
            });
        }
        renderTree(jumpData.project_group_id);

        form.on('select(user-query-select)', function (data) {
            renderTree(data.value);
            jumpData.project_group_id = data.value;
            return false;
        });

        window.refreshTree = function () {
            renderTree(jumpData.project_group_id);
        }
        window.refreshConfigDetail = function () {
            renderConfigDetail();
        }
        window.getConfigDetail = function () {
            return cm.getDoc().getValue();
        }

        $('#configAdd').click(function () {
            layer.open({
                type: 2,
                title: lang.translate("新增配置"),
                shade: 0.1,
                area: ['400px', '400px'],
                content: '/ui/public/add?' + 'project_group_id=' + jumpData.project_group_id,
            })
        });
    })
</script>
</body>
</html>